package com.niit.cms.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.niit.cms.entity.*;
import com.niit.cms.service.*;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class APIController {
    @Resource
    private CourseService courseService;
    @Resource
    private NewsService newsService;
    @Resource
    private ClassificationService classificationService;
    @Resource
    private MyCourseService myCourseService;
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private CartService cartService;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private ProgressService progressService;
    @Resource
    private CatalogService catalogService;
    @Resource
    private VideoService videoService;

    /**
     * @Description: 首页“找课程”发起ajax请求查询查询一级分类下指定条课程
     * @Author: cao_jiaqi
     * @CreateTime: 2022/6/25 13:11
     * @param: dataId 一级分类id
     * @return: java.util.List<com.niit.cms.entity.Course>
     **/
    @GetMapping("queryIndexCourse")
    public List<Course> queryIndexCourse(@RequestParam("dataId") String dataId){
        Integer type = Integer.parseInt(dataId);
        List<Course> courseList = courseService.queryOrderedListByTypeLimit(type,"people_num",7);
        return courseList;
    }
    /**
     * @Description: 首页发起ajax请求查询指定条数据并排序
     * @Author: cao_jiaqi
     * @CreateTime: 2022/6/26 0:53
     * @param: value
     * @return: java.util.List<com.niit.cms.entity.News>
     **/
    @GetMapping("/queryIndexNews")
    public List<News> queryIndexNews(@RequestParam("value") String value){
        //查询最新资讯
        if(value.equals("最新资讯")){
            List<News> newsList = newsService.queryOrderedListByLmit("pubdate", 25);
            System.out.println("newList " + newsList);
            return newsList;
        }
        //查询热门资讯
        if(value.equals("热门资讯")){
            List<News> newsList = newsService.queryOrderedListByLmit("read_num", 25);
            System.out.println("newList " + newsList);
            return newsList;
        }
        //按分类查询指定条数据并排序
        List<News> newsList = newsService.queryOrderedListByTypeLimit(value, "pubdate", 25);
        System.out.println("newList " + newsList);
        return newsList;
    }
    /**
     * @Description: 找课程页面发起ajax请求，根据父分类id查询子分类
     * @Author: cao_jiaqi
     * @CreateTime: 2022/6/28 16:34
     * @return: java.util.List<com.niit.cms.service.ClassificationService>
     **/
    @GetMapping("/querySubClassification")
    public List<Classification> querySubClassification(@RequestParam("dataId") String dataId){
        //System.out.println(dataId);
        Integer parentId = Integer.parseInt(dataId);
        List<Classification> classificationList = classificationService.queryListByParentId(parentId);
        //System.out.println("classificationList = " + classificationList);
        return classificationList;
    }
    /**
     * @Description: 课程详情页发送ajax请求：用户评论前判断是否加入了课程，如果加入了可以评论，否则返回错误信息
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/1 17:39
     * @return: java.lang.String
     **/
    @GetMapping("/queryMyCourse")
    public String queryMyCourse(HttpSession session, @RequestParam("courseId") Integer courseId){
        String msg = "";
        Userinfo userinfo = (Userinfo) session.getAttribute("user");
        if(myCourseService.queryByUidCourseId(userinfo.getId(), courseId) != null){
            msg = "ok";
        }else{
            msg = "您尚未加入课程，不可以评论哦";
        }
        return msg;
    }
    /**
     * @Description: 课程详情页发送ajax请求，更新评论
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/1 18:39
     * @param: myCourse
     * @return: java.lang.String
     **/
    @PutMapping("/updateMyCourse")
    public String updateMyCourse(MyCourse myCourse){
        String msg;
        MyCourse myCourse1 = myCourseService.update(myCourse);
        if(myCourse1 != null){
            msg = "发布成功";
        }else {
            msg = "发布失败";
        }
        return msg;
    }
    /**
     * @Description: 修改密码页面发送ajax请求，修改密码前验证旧密码是否正确
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/2 15:40
     * @return: java.lang.String
     **/
    @GetMapping("/ValidatePwd")
    public String validatePwd(HttpSession session, @RequestParam("oldPwd") String password){
        String msg = "";
        Userinfo userinfo = (Userinfo) session.getAttribute("user");
        if(password.equals(userinfo.getPwd())){
            msg = "密码正确";
        }else{
            msg = "密码错误";
        }
        return msg;
    }
    /**
     * @Description: 修改密码页面发起ajax请求，修改密码
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/2 16:13
     * @param: userinfo
     * @param: session
     * @return: java.lang.String
     **/
    @PutMapping("/updatePwd")
    public String updatePwd(Userinfo userinfo, HttpSession session){
        String msg = "";
        Userinfo u = userinfoService.update(userinfo);
        if(u != null){
            session.setAttribute("user", u);
            msg = "修改密码成功";
        }else{
            msg = "修改密码失败";
        }
        return msg;
    }
    /**
     * @Description: 点击加购发送ajax请求，添加一条购物车记录
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/3 15:49
     * @param: cart
     * @return: java.lang.String
     **/
    @PostMapping("/addCart")
    public String addCart(Cart cart){
        String msg = "";
        //如果已经加过该课程则不能再加购
        Cart c = cartService.queryByUidCourseId(cart.getUid(), cart.getCourseId());
        if(c != null){
            msg = "您已经加购了该课程，不能重复加购";
        }else{
            Cart cart1 = cartService.insert(cart);
            if(cart1 != null){
                msg = "加入购物车成功";
            }else{
                msg = "加入购物车失败";
            }
        }
        return msg;
    }
    /**
     * @Description: 删除单条购物车
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/3 19:55
     * @param: uid
     * @param: courseId
     * @return: java.lang.String
     **/
    @DeleteMapping("/delCart")
    public String delCart(@RequestParam("uid") Integer uid, @RequestParam("courseId") Integer courseId){
        String msg = null;
        boolean result = cartService.deleteByUidCourseId(uid, courseId);
        if(result == true){
            msg = "删除购物车成功";
        }else{
            msg = "删除购物车失败";
        }
        return msg;
    }
    /**
     * @Description: 清空购物车
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/3 19:56
     * @return: java.lang.String
     **/
    @DeleteMapping("/delAllCart")
    public String delAllCart(){
        String msg = null;
        boolean result = cartService.deleteAll();
        if(result == true){
            msg = "清空购物车成功";
        }else{
            msg = "清空购物车失败";
        }
        return msg;
    }
    /**
     * @Description: 添加订单和相应订单详情
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/3 20:49
     * @param: order
     * @param: cartList
     * @return: java.lang.String
     **/
    @RequestMapping("/addOrder")
    public String addOrder(@RequestParam("uid") Integer uid,
                           @RequestParam("sumPrice") Integer sumPrice,
                           @RequestParam(name = "courseId", required = false) Integer courseId){
        String msg = null;
        Order order = new Order();
        order.setUid(uid);
        order.setState("0");
        order.setSumPrice(sumPrice);
        order.setTime(new Date());
        //添加一条订单
        Order order1 = orderService.insert(order);
        List<Cart> cartList = cartService.queryListByUid(uid);
        if(courseId != null){
            //直接购买方式添加订单详情
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOid(order1.getId());
            orderdetail.setCourseId(courseId);
            orderdetailService.insert(orderdetail);
            return String.valueOf(order1.getId());//返回oid
        }else{
            //购物车方式添加订单详情
            for(Cart cart : cartList){
                Orderdetail orderdetail = new Orderdetail();
                orderdetail.setOid(order1.getId());
                orderdetail.setCourseId(cart.getCourseId());
                orderdetailService.insert(orderdetail);
            }
        }
        List<Orderdetail> odlist = orderdetailService.queryListByOid(order1.getId());
        if(order1 != null && odlist.size() == cartList.size()){
            //清空购物车
            cartService.deleteAll();
            //返回oid
            msg = String.valueOf(order1.getId());
        }else{
            msg = "生成订单失败";
        }
        return msg;
    }
    /**
     * @Description: 更新订单状态
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/4 9:22
     * @param: oid
     * @return: java.lang.String
     **/
    @PutMapping("/updateOrderState")
    public String updateOrderState(HttpSession session, @RequestParam("oid") Integer oid){
        String msg = null;
        Order order = orderService.queryById(oid);
        order.setState("1");
        Order o = orderService.update(order);//更新订单状态
        Integer uid = o.getUid();
        //把订单包含的课程加入到我的课程中
        List<Orderdetail> odlist = orderdetailService.queryListByOid(oid);
        for(Orderdetail orderdetail : odlist){
            if(myCourseService.queryByUidCourseId(uid,orderdetail.getCourseId()) == null){
                MyCourse myCourse = new MyCourse();
                myCourse.setCourseId(orderdetail.getCourseId());
                myCourse.setUid(uid);
                myCourse.setState(0);
                myCourse.setCourseProcess(0);
                myCourseService.insert(myCourse);

                //更新课程学习人数
                Course course = courseService.queryById(orderdetail.getCourseId());
                course.setPeopleNum(course.getPeopleNum() + 1);
                System.out.println("course=" + course);
                courseService.update(course);

                //每个课程初始化学习进度
                List<Progress> progressList = progressService.queryListByCourseId(orderdetail.getCourseId());
                if(progressList.isEmpty()){
                    Integer courseId = orderdetail.getCourseId();
                    //该课程下所有目录
                    List<Catalog> catalogList = catalogService.queryListByCourseId(courseId);
                    if(!catalogList.isEmpty()) {
                        //所有视频
                        for (Catalog catalog : catalogList) {
                            List<Video> videoList = videoService.queryListByCatalogId(catalog.getId());
                            if (!videoList.isEmpty()) {
                                for (Video video : videoList) {
                                    Progress progress = new Progress();
                                    progress.setUid(uid);
                                    progress.setCourseId(courseId);
                                    progress.setVid(video.getId());
                                    progress.setState("0");
                                    progressService.insert(progress);
                                }
                            }
                        }
                    }
                }
            }
        }

        if(o != null){
            msg = "订单已支付";
        }else{
            msg = "支付失败";
        }
        return msg;
    }
    /**
     * @Description: 删除订单
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/6 10:40
     * @param: oid
     * @return: java.lang.String
     **/
    @DeleteMapping("/deleteOrder")
    public String deleteOrder(@RequestParam("oid") Integer oid){
        String msg = null;
        //删除该订单所有订单详情
        boolean result = orderdetailService.deleteByOid(oid);
        //删除该订单
        boolean result1 = orderService.deleteById(oid);
        if(result == true && result1 == true){
            msg = "删除订单成功";
        }else{
            msg = "删除订单失败";
        }
        return msg;
    }
    /**
     * @Description: 查询学习进度
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/6 10:40
     * @param: uid
     * @param: vid
     * @param: courseId
     * @return: java.lang.String
     **/
    @GetMapping("/queryProgress")
    public String queryProgress(@RequestParam("uid") Integer uid,
                                @RequestParam("vid") Integer vid,
                                @RequestParam("courseId") Integer courseId){
        String msg = null;
        Progress progress = progressService.queryById(uid, vid, courseId);
        if(progress.getState().equals("0")){
            msg = "未完成";
        }else{
            msg = "已完成";
        }
        return msg;
    }
    /**
     * @Description: 修改学习进度状态
     * @Author: cao_jiaqi
     * @CreateTime: 2022/7/6 13:08
     * @param: uid
     * @param: vid
     * @param: courseId
     * @return: java.lang.String
     **/
    @PutMapping("/updateProgress")
    public String updateProgress(@RequestParam("uid") Integer uid,
                                 @RequestParam("vid") Integer vid,
                                 @RequestParam("courseId") Integer courseId){
        String msg = null;
        Progress progress = progressService.queryById(uid,vid,courseId);
        progress.setState("1");
        Progress p = progressService.update(progress);
        if(p != null){
            msg = "修改学习状态成功";
        }else {
            msg = "修改学习状态失败";
        }
        return msg;
    }
}
